package org.example.kunkun_filter.config;


import org.example.kunkun_filter.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT身份验证过滤器
 * 用于拦截需要身份验证的请求，并从token中提取openid
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    // 不需要身份验证的路径
    private static final String[] EXCLUDED_PATHS = {
            "/auth/wechat-login",
            "/auth/check-token",
            "/error"
    };

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 检查是否为排除的路径
        if (isExcludedPath(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }

        // 从请求头中获取token
        String authHeader = request.getHeader("Authorization");
        String token = null;
        String openid = null;

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            try {
                // 验证token并提取openid
                if (jwtTokenUtil.validateToken(token)) {
                    openid = jwtTokenUtil.getOpenidFromToken(token);
                    // 将openid存储到请求属性中，供后续处理使用
                    request.setAttribute("openid", openid);
                } else {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write("{\"success\":false,\"message\":\"令牌无效或已过期\"}");
                    return;
                }
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"success\":false,\"message\":\"令牌解析失败\"}");
                return;
            }
        } else {
            // 没有提供有效的token
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"success\":false,\"message\":\"未提供有效的认证令牌\"}");
            return;
        }

        // 继续过滤链
        filterChain.doFilter(request, response);
    }

    // 检查请求路径是否在排除列表中
    private boolean isExcludedPath(String path) {
        for (String excludedPath : EXCLUDED_PATHS) {
            if (path.contains(excludedPath)) {
                return true;
            }
        }
        return false;
    }
}